Dear community,
I have a problem with the following loop:
When I run my entire do-file, it stops at these loops and gives the following error:
} is not a valid command name
r(199);
Moreover, it does not create variables variable1_t1, ..., variable1_t5 and variable2_t1, ..., variable2_t5. Instead, it just creates variables t1, t2, t3, t4 and t5. Clearly, stata does not seem to recognize the outer foreach loop. Or rather, it does not seem to recognize the variables variable1 and variable2. Strangely, if I only run the above code section after I got the error from running my entire do-file, the error does not occur and the loops runs smoothly and produce the desired result. Why does it not work on first try when I run the entire do-file?
Finally, later on I have a similar loop that runs through without any problems:
Thanks for your help!
P.S.: I am using stata 17 on macOS Sonoma 14.2
I have a problem with the following loop:
Code:
foreach var in variable1 variable2 { forval x=1(1)5 { gen `var'_t`x' = . forval j=1(1)`x' { bysort id (year): replace `var'_t`x' = `var'[_n-`j'] if year[_n]-year[_n-`j']==`x' } } }
} is not a valid command name
r(199);
Moreover, it does not create variables variable1_t1, ..., variable1_t5 and variable2_t1, ..., variable2_t5. Instead, it just creates variables t1, t2, t3, t4 and t5. Clearly, stata does not seem to recognize the outer foreach loop. Or rather, it does not seem to recognize the variables variable1 and variable2. Strangely, if I only run the above code section after I got the error from running my entire do-file, the error does not occur and the loops runs smoothly and produce the desired result. Why does it not work on first try when I run the entire do-file?
Finally, later on I have a similar loop that runs through without any problems:
Code:
foreach var in variable1 variable2 { forval i=1(1)5 { bysort id (year): gen `var't`i' = `var'[_n-`i'] if year[_n]-year[_n-`i']==`i' } }
P.S.: I am using stata 17 on macOS Sonoma 14.2
Comment